const redis = require('redis');

let client;

const connectRedis = async () => {
  try {
    client = redis.createClient({
      host: process.env.REDIS_HOST || 'localhost',
      port: process.env.REDIS_PORT || 6379,
      password: process.env.REDIS_PASSWORD || undefined,
      retry_strategy: (options) => {
        if (options.error && options.error.code === 'ECONNREFUSED') {
          return new Error('Redis服务器拒绝连接');
        }
        if (options.total_retry_time > 1000 * 60 * 60) {
          return new Error('重试时间超过1小时');
        }
        if (options.attempt > 10) {
          return undefined;
        }
        return Math.min(options.attempt * 100, 3000);
      }
    });

    client.on('error', (err) => {
      console.error('Redis连接错误:', err);
    });

    client.on('connect', () => {
      console.log('✅ Redis连接成功');
    });

    client.on('ready', () => {
      console.log('✅ Redis准备就绪');
    });

    await client.connect();
    
    return client;
  } catch (error) {
    console.error('Redis连接失败:', error);
    throw error;
  }
};

const getClient = () => {
  if (!client) {
    throw new Error('Redis未连接');
  }
  return client;
};

// 缓存工具函数
const cache = {
  // 设置缓存
  async set(key, value, expireTime = 3600) {
    try {
      const client = getClient();
      const serializedValue = typeof value === 'object' ? JSON.stringify(value) : value;
      await client.setEx(key, expireTime, serializedValue);
      return true;
    } catch (error) {
      console.error('设置缓存失败:', error);
      return false;
    }
  },

  // 获取缓存
  async get(key) {
    try {
      const client = getClient();
      const value = await client.get(key);
      if (!value) return null;
      
      try {
        return JSON.parse(value);
      } catch {
        return value;
      }
    } catch (error) {
      console.error('获取缓存失败:', error);
      return null;
    }
  },

  // 删除缓存
  async del(key) {
    try {
      const client = getClient();
      await client.del(key);
      return true;
    } catch (error) {
      console.error('删除缓存失败:', error);
      return false;
    }
  },

  // 检查键是否存在
  async exists(key) {
    try {
      const client = getClient();
      const result = await client.exists(key);
      return result === 1;
    } catch (error) {
      console.error('检查缓存键失败:', error);
      return false;
    }
  },

  // 设置过期时间
  async expire(key, seconds) {
    try {
      const client = getClient();
      await client.expire(key, seconds);
      return true;
    } catch (error) {
      console.error('设置过期时间失败:', error);
      return false;
    }
  }
};

module.exports = {
  connectRedis,
  getClient,
  cache
}; 